package com.insurance.common.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import javax.crypto.SecretKey;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class JwtOperatorUtil {

    private static String secret = "aaabbbcccdddeeefffggghhhiiijjjkkk";
    /**
     * 有效期，单位秒
     * - 默认2小时
     */
    private static Long expirationTimeInSecond = 7200L;

    /**
     * 从token中获取claim
     *
     * @param token token
     * @return claim
     */
    public static Claims getClaimsFromToken(String token) {
        try {
            return Jwts.parser()
                .setSigningKey(secret.getBytes())
                .parseClaimsJws(token)
                .getBody();
        } catch (ExpiredJwtException | UnsupportedJwtException | MalformedJwtException | IllegalArgumentException e) {
            log.error("token解析错误", e);
            throw new IllegalArgumentException("Token invalided.");
        }
    }

    /**
     * 获取token的过期时间
     *
     * @param token token
     * @return 过期时间
     */
    public static Date getExpirationDateFromToken(String token) {
        return getClaimsFromToken(token)
            .getExpiration();
    }

    /**
     * 判断token是否过期
     *
     * @param token token
     * @return 已过期返回true，未过期返回false
     */
    public static Boolean isTokenExpired(String token) {
        Date expiration = getExpirationDateFromToken(token);
        return expiration.before(new Date());
    }

    /**
     * 计算token的过期时间
     *
     * @return 过期时间
     */
    public static Date getExpirationTime() {
        return new Date(System.currentTimeMillis() + expirationTimeInSecond * 1000);
    }

    /**
     * 为指定用户生成token
     *
     * @param claims 用户信息
     * @return token
     */
    public static String generateToken(Map<String, Object> claims) {
        Date createdTime = new Date();
        Date expirationTime = getExpirationTime();

        byte[] keyBytes = secret.getBytes();
        SecretKey key = Keys.hmacShaKeyFor(keyBytes);

        return Jwts.builder()
            .setClaims(claims)
            .setIssuedAt(createdTime)
            .setExpiration(expirationTime)
            // 你也可以改用你喜欢的算法
            // 支持的算法详见：https://github.com/jwtk/jjwt#features
            .signWith(key, SignatureAlgorithm.HS256)
            .compact();
    }

    /**
     * 判断token是否非法
     *
     * @param token token
     * @return 未过期返回true，否则返回false
     */
    public static Boolean validateToken(String token) {
        try {
            return !isTokenExpired(token);
        } catch (Exception e) {
            log.error("【判断token是否合法异常】", e);
            return false;
        }
    }

    /**
     * 获取用户Id
     *
     * @param token
     * @return
     */
    public static String getUserId(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.containsKey("userId") ? claims.get("userId").toString() : "";
    }

    /**
     * 获取用户姓名
     *
     * @param token
     * @return
     */
    public static String getUserName(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.containsKey("userName") ? claims.get("userName").toString() : "";
    }

    /**
     * 获取用户来源
     *
     * @param token
     * @return
     */
    public static String getAppId(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.containsKey("appId") ? claims.get("appId").toString() : "";
    }

    /**
     * 获取用户身份证号
     *
     * @param token
     * @return
     */
    public static String getCardId(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.containsKey("cardId") ? claims.get("cardId").toString() : "";
    }

    /**
     * 获取用户手机号
     *
     * @param token
     * @return
     */
    public static String getTelephone(String token){
        Claims claims = getClaimsFromToken(token);
        return claims.containsKey("telephone") ? claims.get("telephone").toString() : "";
    }

    public static String getToken(HttpServletRequest request){
        try {
            String token = request.getHeader("accessToken");
            if(!StringUtils.isBlank(token)){
                return token;
            }
            return "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String getUserId(HttpServletRequest request){
        try {
            String token = getToken(request);
            if(!StringUtils.isBlank(token)){
                return getUserId(token);
            }else{
                return "";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取appId
     *
     * @param request
     * @return
     */
    public static String getAppId(HttpServletRequest request){
        return getAppId(getToken(request));
    }

    /**
     * 获取权限字符串集合
     *
     * @param request
     * @return
     */
    public static List<String> getPermissionList(HttpServletRequest request){
        Claims claims = getClaimsFromToken(getToken(request));
        List<String> permission = (List<String>) claims.get("permission");
        return permission;
    }

}